<!-- 作业管理-工作计划汇总 -->
<template>
    <div class="questionBank">
        <!-- 搜索 -->
        <el-card class="box-card" body-style="display: flex; align-items: center; justify-content: space-between;">
            <div class="cardBody">
                <div class="cardBody1">
                    汇总日期:
                    <el-date-picker v-model="valueData" type="date" placeholder="选择日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
                </div>
                <div>
                    <el-button type="primary" size="small" @click="onSearch">搜索</el-button>
                </div>
            </div>

            <div class="cardBodyR">
                <el-button type="primary" plain icon="el-icon-download" size="small" @click="exportExcel">导出表格</el-button>
            </div>
        </el-card>

        <!-- 列表 -->
        <el-card class="boxCard">
            <el-table ref="tableRef" :data="tableData" stripe style="width: 100%" :height="tableHeight" border>
                <el-table-column :label="deptName + '施工计划'" align="center" >
                    <el-table-column prop="planName" label="作业名称" align="center" ></el-table-column>
                    <el-table-column prop="workContent" label="作业内容" align="center" ></el-table-column>
                    <el-table-column prop="creator.nickname" label="工作负责人" align="center" ></el-table-column>
                    <el-table-column prop="workers" label="工作班成员" align="center" >
                        <template slot-scope="scope">
                            <span v-for="(item,index) in scope.row.workers">
                                {{((index != 0 ? ',' : '') + (item.empName || '-'))}}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="machCmdsInfoList" label="投入设备" align="center" >
                        <template slot-scope="scope">
                            <span v-for="(item,index) in scope.row.machCmdsInfoList">
                                {{((index != 0 ? ',' : '') + item)}}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="risk" label="危险点" align="center" ></el-table-column>
                    <el-table-column prop="measures" label="预控措施" align="center" min-width="200"></el-table-column>
                    <el-table-column prop="riskLevel" label="风险等级" align="center" >
                        <template slot-scope="scope">
                            <el-tag type="success" v-if="scope.row.riskLevel == 3" size="small">一般风险</el-tag>
                            <el-tag type="warning" v-if="scope.row.riskLevel == 2" size="small">较大风险</el-tag>
                            <el-tag type="danger" v-if="scope.row.riskLevel == 1" size="small">重大风险</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="旁站监护人员" align="center">
                        <!-- guardian1Id分包 guardian2Id总包 guardian3Id监理 guardian4Id业主-->
                        <el-table-column prop="guardian1" label="分包" align="center" width="150">
                            <template slot-scope="scope">
                                <!-- <div v-for="(item, index) in scope.row.guardian1" :key="index">
                                    {{((index!=0?',':'') + (item.empName || '-'))}}
                                </div> -->
                                {{
                                    scope.row.guardian1Id ? personNames(scope.row.guardian1Id) : ''
                                }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="guardian2" label="总包" align="center" width="150">
                            <template slot-scope="scope">
                                <!-- <div v-for="(item, index) in scope.row.guardian2" :key="index">
                                    {{((index!=0?',':'') + (item.empName || '-'))}}
                                </div> -->
                                {{
                                    scope.row.guardian2Id ? personNames(scope.row.guardian2Id) : ''
                                }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="guardian3" label="监理" align="center" width="150">
                            <template slot-scope="scope">
                                <!-- <div v-for="(item, index) in scope.row.guardian3" :key="index">
                                    {{((index!=0?',':'') + (item.empName || '-'))}}
                                </div> -->
                                {{
                                    scope.row.guardian3Id ? personNames(scope.row.guardian3Id) : ''
                                }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="guardian4" label="业主" align="center" width="150">
                            <template slot-scope="scope">
                                <!-- <div v-for="(item, index) in scope.row.guardian4" :key="index">
                                    {{((index!=0?',':'') + (item.empName || '-'))}}
                                </div> -->
                                {{
                                    scope.row.guardian4Id ? personNames(scope.row.guardian4Id) : ''
                                }}
                            </template>
                        </el-table-column>
                    </el-table-column>
                </el-table-column>
            </el-table>
            <!-- <div class="boxCard_-pagination">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="currentPage" :page-sizes="[10, 30, 50, 100]" :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper" :total="total">
                </el-pagination>
            </div> -->
        </el-card>

    </div>
</template>

<script>
    import {
        apiWorkPlanWorkPageList,
        getApiEmpList
    } from "@/api/apifox.js";

    import * as XLSX from 'xlsx'
    import { saveAs } from 'file-saver'

    export default {
        components: {},
        data() {
            return {
                tableHeight: window.innerHeight - 300,
                // 搜索
                valueData: '',

                tableData: [], // 列表
                currentPage: 1, // 当前页数
                pageSize: 9999, // 每页显示条目个数
                total: 0, // 总条目数

                projectId: null,
                deptName: '',
                ApiEmpList: [], // 查询所有人员（不分页）
            };
        },
        computed: {
            porjectObject() {
                return this.$store.state.porjectObject;
            }
        },
        watch: {
            porjectObject(val, oldVal) {
                if (val.deptId != oldVal.deptId) {
                    this.projectId = val.deptId;
                    this.deptName = val.name;
                    this.currentPage = 1;
                    // this.getList();
                }
            }
        },
        created() {

        },
        mounted() {
            this.projectId = this.$store.state.porjectObject.deptId;
            this.deptName = this.$store.state.porjectObject.name;
            // this.getList();
            this.onApiEmpList();
        },
        methods: {
            exportExcel() {
                if(this.valueData == '') {
                    this.$Message.warning('请选择汇总日期!');
                    return
                }
                if(this.tableData.length == 0) {
                    this.$Message.warning('请先生成施工计划!');
                    return
                }

                // 确认XLSX已正确导入
                if (!XLSX || !XLSX.utils) {
                    this.$Message.warning('XLSX库导入失败!');
                    return
                }

                this.$nextTick(() => {

                    // 1. 获取表头和表格体的 DOM
                    const tableRef = this.$refs.tableRef.$el;
                    // 表头 DOM（.el-table__header-wrapper 下的 table）
                    const headerTable = tableRef.querySelector('.el-table__header-wrapper table').cloneNode(true);
                    // 表格体 DOM（.el-table__body-wrapper 下的 table）
                    const bodyTable = tableRef.querySelector('.el-table__body-wrapper table').cloneNode(true);

                    if (!headerTable || !bodyTable) {
                        this.$Message.warning('未找到表头或表格体 DOM!');
                        return;
                    }

                    // 2. 合并表头和表格体（关键：手动拼接 thead 和 tbody）
                    // 复制表头的 thead
                    const thead = headerTable.querySelector('thead').cloneNode(true);
                    // 获取表格体的 tbody
                    const tbody = bodyTable.querySelector('tbody').cloneNode(true);

                    // 创建一个临时表格，用于合并表头和表体
                    const tempTable = document.createElement('table');
                    tempTable.appendChild(thead); // 加入表头
                    tempTable.appendChild(tbody); // 加入表体

                    // 3. 转换为工作表（使用合并后的临时表格）
                    const worksheet = XLSX.utils.table_to_sheet(tempTable);
                    const workbook = XLSX.utils.book_new();
                    XLSX.utils.book_append_sheet(workbook, worksheet, '表格数据');

                    // 4. 下载
                    const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
                    const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
                    saveAs(blob, `${this.deptName}施工计划-${this.valueData}.xlsx`);

                });
            },
            onSearch() {
                this.currentPage = 1;
                this.getList();
            },
            getList() {
                console.log(this.valueData);
                if(this.valueData == '' || this.valueData == null) {
                    this.$Message.warning('请选择汇总日期!');
                    return
                }
                apiWorkPlanWorkPageList({
                    pageSize: this.pageSize, // 分页大小
                    pageNum: this.currentPage, // 分页页码
                    // projectId: this.projectId, //
                    // createTimeBegin: (this.valueData + ' 00:00:00'), // 创建时间开始（用于工作计划创建时间查询）
                    // createTimeEnd: (this.valueData + ' 23:59:59'), // 创建时间结束（用于工作计划创建时间查询）

                    startTimeBegin: `${this.valueData} 00:00:00`, // 工作计划开始时间-起始
                    startTimeEnd: `${this.valueData} 23:59:59`, // 工作计划开始时间-结束
                    /* endTimeBegin: (this.valueData + ' 00:00:00'), // 工作计划结束时间-起始
                    endTimeEnd: (this.valueData + ' 23:59:59'), // 工作计划结束时间-结束 */
                    auditStatus: 2,
                }).then(res => {
                    if (res.code == 200) {
                        this.tableData = res.data.list
                        this.total = res.data.total
                    } else {
                        this.$Message.warning(res.msg);
                    }
                }).catch(error => {
                    console.log(error);
                });
            },

            /* 详情事件 */
            onDetails(row) {
                this.$router.push({
                    path: "/HomeworkManagement/SummaryDetails",
                    query: {
                        row: row.val3
                    }
                });
            },

            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.pageSize = val;
                this.getList();
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.currentPage = val;
                this.getList();
            },

            onApiEmpList() {
                getApiEmpList({
                    deptId: this.projectId
                }).then(res => {
                    console.log('查询所有人员（不分页）：', res);
                    if (res.code == 200) {
                        this.ApiEmpList = res.data.list
                    } else {
                        this.$Message.warning(res.msg);
                    }
                }).catch(error => {
                    console.log(error);
                });
            },

            personNames(idStr) {
                // 容错处理：如果传入的idStr为空或非字符串，直接返回空数组
                if (!idStr || typeof idStr !== 'string') {
                    return [];
                }

                // 拆分ID字符串为数组，并过滤空字符串（避免因输入类似 '11,,34' 导致的空ID）
                const ids = idStr.split(',').filter(id => id.trim() != '');

                // 遍历ID数组查询名称
                const nameList = ids.map(id => {
                    // 若ApiEmpList不存在，直接返回未知
                    if (!this.ApiEmpList || !Array.isArray(this.ApiEmpList)) {
                      return '';
                    }
                    // 查找对应人员（trim处理id，避免前后空格导致匹配失败）
                    const person = this.ApiEmpList.find(p => p.empId == id.trim());
                    return person ? person.empName : '';
                });

                return nameList.join(',');
            },
        }
    };
</script>

<style lang="scss" scoped>
    .questionBank {
        padding: 20px;

        .box-card {

            .cardBody {
                display: flex;
                align-items: center;
                gap: 15px;

                .cardBody1 {
                    display: flex;
                    align-items: center;
                    gap: 10px;

                   .ecard_val {
                       width: 200px;
                   }
                }
            }

            .cardBodyR {

            }
        }

        .boxCard {
            margin-top: 20px;

            .boxCard_-pagination {
                display: flex;
                align-items: center;
                justify-content: center;
                margin-top: 20px;
            }
        }

        .abcdCl {
            width: 80%;
        }

        .abcdCls {
            display: flex;
            align-items: center;
            gap: 10px;
        }
    }
</style>
